package com.ruoyi.web.controller.hrm;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.FileUploadInfo;
import com.ruoyi.system.domain.EmploymentContract;
import com.ruoyi.system.service.IFileUploadService;
import com.ruoyi.system.service.IEmploymentContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @date 2021-07-05
 */
@Controller
@RequestMapping("/hrm/employmentContract")
public class EmploymentContractController extends BaseController
{
    private String prefix = "hrm/employmentContract";

    @Autowired
    private IFileUploadService fileUploadService;

    @Autowired
    private IEmploymentContractService employmentContractService;

    @GetMapping()
    public String toMain(ModelMap modelMap) {
        return prefix + "/main";
    }

    /**
     * 用工合同列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(EmploymentContract employmentContract)
    {
        startPage();
        List<EmploymentContract> employmentContractList = employmentContractService.selectEmploymentContractList(employmentContract);
        //统计附件数
        for (EmploymentContract ec:employmentContractList) {
            Integer count = fileUploadService.getFileCountByKey(ec.getEcId());
            ec.setFileCount(count);
        }
        return getDataTable(employmentContractList);
    }

    /**
     * 跳转上传附件
     * @param modelMap
     * @return
     */
    @GetMapping("/toUpload/{ecId}")
    public String toUpload(@PathVariable String ecId, ModelMap modelMap) {
        List<FileUploadInfo> fileUploadInfos = fileUploadService.getFileUploadListByKey(ecId);
//        for(FileUploadInfo file:fileUploadInfos){
//            file.setFilePath(file.getFilePath().replaceAll("/profile/EmploymentContract",Global.getEmploymentContractPath()));
//        }
        modelMap.put("ecId",ecId);
        modelMap.put("fileInfos",fileUploadInfos);
        return prefix + "/contractUpload";
    }

    @PostMapping("/contractUpload")
    @ResponseBody
    public AjaxResult contractUpload(MultipartFile file) {
        String filePath = "";
        try {
            filePath = FileUploadUtils.upload(Global.getEmploymentContractPath(),file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(file.getOriginalFilename(),filePath);
    }
    @PostMapping("/changePath")
    @ResponseBody
    public AjaxResult changePath(String ecId,String filePath,String fileName) {
        try{
            FileUploadInfo fileUploadInfo = new FileUploadInfo();
            fileUploadInfo.setFileId(UUID.randomUUID().toString().replaceAll("-",""));
            fileUploadInfo.setFileName(fileName);
            fileUploadInfo.setFilePath(filePath);
            fileUploadInfo.setFileType("4");  //用工合同
            fileUploadInfo.setStatus("1");  //有效
            fileUploadInfo.setBelongKey(ecId);
            fileUploadService.insertFileUpload(fileUploadInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @PostMapping("/removeAnnex")
    @ResponseBody
    public AjaxResult removeAnnex(String key) {
        //String ecId,String filePath    目前用不上
        try{
            fileUploadService.deleteFile(key);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("文件删除失败");
        }
        return AjaxResult.success();
    }

    /**
     * 跳转新增
     * @param modelMap
     * @return
     */
    @GetMapping("/add")
    public String toAdd(ModelMap modelMap) {
        return prefix + "/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(EmploymentContract employmentContract) {
        try{
            employmentContractService.insertEmploymentContract(employmentContract);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success();
    }

    /**
     * 跳转新增
     * @return
     */
    @GetMapping("/edit/{ecId}")
    public String toEdit(@PathVariable String ecId,ModelMap modelMap) {
        EmploymentContract employmentContract = employmentContractService.getEmploymentContractById(ecId);
        modelMap.put("employmentContract",employmentContract);
        return prefix + "/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(EmploymentContract employmentContract) {
        try{
            employmentContractService.updateEmploymentContract(employmentContract);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success();
    }


    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try{
            employmentContractService.removeEmploymentContract(ids);
            fileUploadService.deleteAll(ids);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success();
    }

    /**
     *
     *导出
     * @return
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(EmploymentContract employmentContract,String ids) {
        List<EmploymentContract> pcList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] ecIds = Convert.toStrArray(ids);
            for(String ecId:ecIds){
                EmploymentContract pc = employmentContractService.getEmploymentContractById(ecId);
                pcList.add(pc);
            }
        }else{
            pcList = employmentContractService.selectEmploymentContractList(employmentContract);
        }
        ExcelUtil<EmploymentContract> util = new ExcelUtil(EmploymentContract.class);
        return util.exportExcel(pcList, "用工合同");
    }
    /**
     * 导入
     * @return
     */
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importEmploymentContract(MultipartFile file)  {
        ExcelUtil<EmploymentContract> util = new ExcelUtil<>(EmploymentContract.class);
        List<EmploymentContract> lists = null;
        try {
            lists = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("excel解析错误");
        }
        //校验数据
        String message =employmentContractService.importEmploymentContract(lists);
        return AjaxResult.success(message);
    }
    /**
     * 下载用工合同模板
     * @return
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<EmploymentContract> util = new ExcelUtil<EmploymentContract>(EmploymentContract.class);
        return util.importTemplateExcel("用工合同");
    }

    @PostMapping("/downloadContract")
    @ResponseBody
    public AjaxResult downloadContract(String ecId) {
        List<FileUploadInfo> fileUploadInfos = fileUploadService.getFileUploadListByKey(ecId);
        String contractPath = "/profile/employmentContract";
        File dir = new File(Global.getDownloadPath()+ecId);
        if(!dir.exists()){
            dir.mkdirs();
        }
        if(fileUploadInfos!=null&&fileUploadInfos.size()>0){
            //执行循环将需要下载的文件拷贝到下载目录下
            for(FileUploadInfo fileUploadInfo:fileUploadInfos){
                String newPath = fileUploadInfo.getFilePath().replaceAll(contractPath,Global.getEmploymentContractPath());
                File file = new File(newPath);
                File newFile = new File(dir + File.separator + fileUploadInfo.getFileName());
                try {
                    Files.copy(file.toPath(),newFile.toPath());
//                    fileUploadInfo.setFilePath(newFile.toPath().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            return AjaxResult.error("无附件！");
        }
        return AjaxResult.success("success",ecId);
    }

    @GetMapping("/downloadContract")
    public void downloadContract(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try{
            EmploymentContract pc = employmentContractService.getEmploymentContractById(fileName);
            String downloadName = pc.getNum()+":"+ pc.getName() + "用工合同附件.zip";
            String sourceFilePath = Global.getDownloadPath() + fileName;
            String zipOutFilePath = Global.getDownloadPath() + downloadName;
            FileUtils.createZip(sourceFilePath,zipOutFilePath);
            try{
                response.setHeader("Content-Type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.setFileDownloadHeader(request,downloadName));
                FileUtils.writeBytes(zipOutFilePath,response.getOutputStream());
            }finally {
                try{
                    File zfile = new File(zipOutFilePath);
                    zfile.delete();
                    File sqlFile = new File(sourceFilePath);
                    FileUtils.deleteDir(sqlFile);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
